import { BlackBoard } from "./BlackBoard/Blackboard";

interface options {
    ignoreCache?: boolean;
    progress?: Function;
}
/** 导入单个 Prefab 的方式，异步的 */
export function findPrefab(
    path: string,
    { ignoreCache = false, progress }: options = {}
): Promise<Laya.Prefab> {
    if (!/\.prefab$/i.test(path)) {
        path += ".prefab";
    }
    return new Promise((resolve) => {
        Laya.loader.load(
            `prefab/${path}`,
            Laya.Handler.create(null, (prefab: Laya.Prefab) => {
                resolve(prefab);
            }),
            progress ? Laya.Handler.create(null, progress) : null,
            Laya.Loader.PREFAB,
            1,
            true,
            "laya-system-prefab",
            ignoreCache
        );
    });
}

/** 加载一个场景内需要导入的 Prefab 并生成一个 BlackBoard */
export async function loadPrefabAsBlackBoard<
    T extends {
        [key: string]: options;
    }
>(input: T) {
    const all = (await Object.entries(input).reduce(
        async (template, [path, options]) => {
            const col = await template;
            col[path] = await findPrefab(path, options)!;
            return col;
        },
        Promise.resolve({} as { [key: string]: Laya.Prefab })
    )) as { [key in keyof T]: Laya.Prefab };

    return new BlackBoard<typeof all>(all);
}
